﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class views_cartonline : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (this.IsPostBack) return;
        load_cart();
    }

    public void load_cart()
    {
        products gio = (products)Session["Cart"];
        if (gio != null)
        {
            this.rpt_giohang.DataSource = gio.Data;
            this.rpt_giohang.DataBind();
            lbSubtotal.Text = gio.Subtotal.ToString();
        }
        if (Session["user"] != null)
        {
            DataTable Cus = (DataTable)Session["user"];
            txtfullname.Text = Cus.Rows[0]["customername"].ToString();
            //txtnote.Text = Cus.Rows[0]["note"].ToString();
            txtfone.Text = Cus.Rows[0]["phone"].ToString();
            txtaddress.Text = Cus.Rows[0]["address"].ToString();
            txtemail.Text = Cus.Rows[0]["email"].ToString();
        }
    }
    protected void rpt_giohang_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "UpdateQuantity")
        {
            TextBox _txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");
            products gio = (products)Session["Cart"];

            if (gio != null && _txtQuantity != null)
            {
                int _quantity = 0;
                int.TryParse(_txtQuantity.Text, out _quantity);
                gio.UpdateQuantity(e.CommandArgument.ToString(), _quantity);
                load_cart();
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["user"] != null)
            {
                products gio = (products)Session["Cart"];
                DataTable dtCart = new DataTable();
                DataTable Cus = (DataTable)Session["user"];

                int customerid = int.Parse(Cus.Rows[0]["customerid"].ToString());
                if (insertOrder(customerid, DateTime.Parse(txtdeliverydate.Text), txtnote.Text, txtaddress2.Text, gio.Total, gio.Total, 0) == true)
                {
                    dtCart = gio.Data;
                    int proid = productid();
                    for (int i = 0; i < dtCart.Rows.Count; i++)
                    {

                        insertOrderDetail(proid, int.Parse(dtCart.Rows[i]["ID"].ToString()), int.Parse(dtCart.Rows[i]["Quantity"].ToString()), txtnote.Text);
                    }
                }
                Response.Write(@"<script language='javascript'>alert('Đặt hàng thành công!');</script>");
            }
            else
            {
                Response.Write("<script>window.open('../index.aspx?log=cart','_parent');</script>");
            }
        }
        catch { Response.Write(@"<script language='javascript'>alert('Đặt hàng thất bại!\nXin vui lòng thử lại!');</script>"); }
    }
    public bool insertOrder(int customerid, DateTime deliverydate, string note, string deliveryaddress, float total, float totalpayment, int status)
    {
        DataProvider data = new DataProvider();
        SqlConnection conn = data.Connect();
        try
        {
            SqlCommand cmd = new SqlCommand("sp_orders_insert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@customerid", customerid);
            cmd.Parameters.AddWithValue("@deliverydate", deliverydate);
            cmd.Parameters.AddWithValue("@note", note);
            cmd.Parameters.AddWithValue("@deliveryaddress", deliveryaddress);
            cmd.Parameters.AddWithValue("@total", total);
            cmd.Parameters.AddWithValue("@totalpayment", totalpayment);
            cmd.Parameters.AddWithValue("@status", status);

            cmd.ExecuteNonQuery();

            return true;

        }
        catch
        {
            return false;
        }
        finally { conn.Close(); }
    }
    public bool insertOrderDetail(int orderid, int productid, int quality, string note1)
    {
        DataProvider data = new DataProvider();
        SqlConnection conn = data.Connect();
        try
        {
            SqlCommand cmd = new SqlCommand("sp_order_detail_insert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@orderid", orderid);
            cmd.Parameters.AddWithValue("@productid", productid);
            cmd.Parameters.AddWithValue("@quality", quality);
            cmd.Parameters.AddWithValue("@note1", note1);

            cmd.ExecuteNonQuery();

            return true;

        }
        catch
        {
            return false;
        }
        finally { conn.Close(); }
    }
    public int productid()
    {
        DataProvider data = new DataProvider();
        SqlConnection conn = data.Connect();
        DataTable dt = new DataTable();
        try
        {
            SqlCommand cmd = new SqlCommand("SELECT max([orderid]) as orderid FROM [db_flower].[dbo].[Orders]", conn);
            cmd.CommandType = CommandType.Text;
            dt.Load(cmd.ExecuteReader());

            return int.Parse(dt.Rows[0]["orderid"].ToString());
        }
        catch
        {
            return 0;
        }
        finally { conn.Close(); }
    }
}